// packageStudent/pages/user/info/index.js
import Config from "../../../main.config";
import {isInputEmpty, timesToDate} from "../../../utils/Util";
import {chooseImage} from "../../../utils/Wx";
import {getRegisterDetail, createUser, editUser} from "../../../service/Student";
import {uploader} from "../../../service/Common";
import {getStorageSync} from "../../../utils/Storage";
import Notify from "@vant/weapp/notify/notify";
import Toast from "@vant/weapp/toast/toast";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        /*--表单数据--*/
        logo: { //头像
            src: "",
            id: ""
        },
        sex: "男", //性别
        name: "", //姓名
        city: "", //现居城市
        birthday: {
            title: "出生年月",
            value: ""
        },

        /*--组件数据--*/
        datePicker: { //选择器
            show: false,
            title: "",  //选择器标题
            currentDate: new Date(1988, 6, 1).getTime(),
            minDate: new Date(1970, 1, 1).getTime(),
            maxDate: new Date(2002, 1, 1).getTime(),
        },
        region: { //区域选择器
            show: false,
            value: ""
        },
        submitButton: { //提交按钮状态
            loading: false,
            text: "保存"
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (options.todo === "create") { //创建用户
            this.setData({
                "submitButton.text": "下一步",
                isCreate: true
            })
        } else { //获取员工用户信息
            this.getStudentDetail();
        }
    },

    /*
    * 获取员工用户注册信息
    * */
    getStudentDetail: async function () {
        try {
            let userId = getStorageSync(Config.storage.userInfo + ".userId");
            let detail = await getRegisterDetail(userId);
            let logoUrl = Config.api.downLoad + "?fileId=" + detail.logo;
            this.data._studentDetail = detail;
            detail ? this.setData({
                "logo.id": detail.logo,
                "logo.src": logoUrl,
                sex: detail.sex,
                name: detail.name,
                city: detail.city.split(",")[1],
                "birthday.value": detail.birthday,
                "region.value": detail.city
            }) : null
        } catch (e) {
            console.error(e)
        }
    },

    /*
    * 图片上传
    * */
    bindUploaderLogo: async function () {
        try {
            let tempFilePaths = await chooseImage();
            Toast.loading({
                message: "图片上传中...",
                duration: 0
            });
            this.data.logo.id = await uploader(tempFilePaths[0]);
            this.setData({"logo.src": tempFilePaths});
            Toast.clear();
        } catch (e) {
            e.errMsg !== "chooseImage:fail cancel" ? Toast.fail("上传失败") : null;
            console.error(e)
        }
    },

    /*
    * 性别切换监听函数
    * */
    onGenderChange: function (e) {
        let value = e.detail.value;
        this.setData({sex: value});
    },

    /*
   * 监听开关状态切换
   * */
    onSwitchChange() {
        let sex = this.data.sex;
        this.setData({
            sex: sex === "男" ? "女" : "男"
        })
    },

    /*
    * input 输入监听
    * */
    onInput: function (e) {
        let name = e.currentTarget.dataset.name;
        let value = e.detail
        this.setData({[name]: value})
    },

    /*
    * 获取定位信息
    * */
    getLocationRegion: function () {
        this.setData({"region.loading": true});
    },
    onLocation: function (e) {
        let detail = e.detail;
        if (Object.keys(detail).length > 0) {
            this.setData({
                "region.value": detail.region,
                city: detail.region.split(",")[1],
                addressDetail: detail.address
            })
        } else {
            this.setData({"region.show": true})
        }
    },
    // 区域选择
    onSelectRegion: function (e) {
        let detail = e.detail;
        this.setData({"region.show": false});
        if (!detail) return false;
        this.setData({
            "region.value": detail,
            city: detail.split(",")[1]
        })
    },

    /*
    * 日期选择器
    * 选择器展开
    * */
    bindShowDatePicker: function (e) {
        let name = e.currentTarget.dataset.name;
        let title = this.data[name].title;
        this.setData({
            "datePicker.show": true,
            "datePicker.title": title
        })
    },
    // 选择器选择
    onDatePickerConfirm: function (e) {
        let value = e.detail;
        this.setData({
            "datePicker.show": false,
            "birthday.value": timesToDate(value).substr(0, 7)
        })
    },
    // 选择器关闭
    onDatePickerCancel: function (e) {
        this.setData({"datePicker.show": false})
    },

    /*
    * 点击提交按钮
    * */
    onSubmitButton: async function () {
        try {
            let logo = this.data.logo.id;
            let sex = this.data.sex;
            let name = this.data.name;
            let city = this.data.region.value;
            let birthday = this.data.birthday.value;
            let isLoading = this.data.submitButton.loading;
            if (isLoading) { //防重复
                return false
            } else if (!logo) {
                Notify("请上用户头像");
                return false
            } else if (!isInputEmpty(name)) {
                Notify("请填写您的姓名");
                return false
            } else if (!city) {
                Notify("请选择所在地");
                return false
            } else if (!birthday) {
                Notify("请选择出生日期");
                return false
            } else{
                let studentDetail = this.data._studentDetail;
                let studentId = studentDetail ? studentDetail.id : null;
                let postData = {
                    logo,
                    name,
                    sex,
                    city,
                    birthday,
                    status: 1
                }
                this.setData({"submitButton.loading": true});
                if (studentId) { //编辑
                    postData.id = studentId;
                    await editUser(postData);
                    Toast.success("保存成功！");
                    setTimeout(function () {
                        wx.navigateBack()
                    }, 1500)
                } else { //创建
                    await createUser(postData);
                    wx.redirectTo({
                        url: "/packageStudent/pages/education/index?todo=create"
                    })
                }
            }
        } catch (e) {
            console.error(e)
        } finally {
            this.setData({"submitButton.loading": false});
        }
    },

})